package com.lvcoding.cloud.common.security.auth;

import cn.hutool.core.util.ObjectUtil;
import com.lvcoding.cloud.api.entity.SysUser;
import com.lvcoding.cloud.api.feign.UserFeign;
import com.lvcoding.cloud.common.core.exception.BaseException;
import com.lvcoding.cloud.common.core.response.Res;
import lombok.AllArgsConstructor;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Component
@AllArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {

    private final UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Res<SysUser> res = userFeign.userInfo(username);
        //校验
        validateUser(res);
        //组装UserDetails对象
        return createUserDetails(res);
    }

    private void validateUser(Res<SysUser> res) {
        if(ObjectUtil.isEmpty(res) || ObjectUtil.isEmpty(res.getData())){
            throw new BaseException("用户名不能为空");
        }
    }

    private UserDetails createUserDetails(Res<SysUser> res) {
        CommonUser commonUser = new CommonUser();
        commonUser.setSysUser(res.getData());

        //角色集合
        String roles = "ADMIN,CUSTOMER";
        //权限集合
        String permissions = "sys:user:view,sys:user:add,sys:user:update,sys:user:delete";
        commonUser.setRoles(StringUtils.commaDelimitedListToSet(roles));
        commonUser.setPermissions(StringUtils.commaDelimitedListToSet(permissions));
        commonUser.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(roles+","+permissions));
        return commonUser;
    }
}
